package org.tagging.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.tagging.exception.UnSupportedLanguageException;
import org.tagging.model.Tagging;
import org.tagging.service.TaggingService;
import org.tagging.service.factory.TaggingServiceFactory;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/tagging/export")
@Api(tags = "导出数据")
public class ExportController {

    private static final Logger logger = LoggerFactory.getLogger(ExportController.class);

    @Autowired
    private TaggingServiceFactory taggingServiceFactory;

    @ApiOperation(value = "导出数据", notes = "所需权限(管理员或data_export)（仅传入startTime就会获取该开始时间后的所有被标注了的数据;\r\n" +
            "仅传endTime就会获取该结束时之间前所有标注过了的的数据;startTime和endTime都传入就会获取该段区间内的标注的数据）\r\n" +
            "mode=1时会导出所有的数据，因此传入的时间均无效，包括未被标注以及被标注的，因此会比较慢，上万条标注信息;\" +\n" +
            "\r\nmode=0时会开启过滤，即startTime以及endTime有效且默认仅导出被修改过了的标注信息\r\n" +
            "默认mode=0，可不传入该参数；若不传入时间则导出所有标注过了的数据",produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语种->malay/indonesian/philippines", required = true),
            @ApiImplicitParam(name = "startTime", value = "开始时间格式(2021-02-05 18:15:29)", required = false),
            @ApiImplicitParam(name = "endTime", value = "结束时间格式(2021-02-05 19:00:00)", required = false),
            @ApiImplicitParam(name = "mode", value = "模式,mode=1时会导出所有的数据，因此传入的时间均无效，包括未被标注以及被标注的，因此会比较慢，上万条标注信息;" +
                    "\r\nmode=0时会开启过滤，即startTime以及endTime有效且默认仅导出被修改过了的标注信息")
    })
    @GetMapping("/{language}")
//    @PreAuthorize("hasAnyRole('ADMIN') or hasAnyAuthority('data_export')")
    public void export(@PathVariable(value = "language") String language,
                       @RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
                       @RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
                       @RequestParam(value = "mode", defaultValue = "0") Integer mode,
                       @ApiIgnore HttpServletResponse response) throws UnSupportedLanguageException, IOException {
        TaggingService<? extends Tagging> taggingService = taggingServiceFactory.getTaggingService(language);
        Workbook workbook = taggingService.constructWorkbookByTimePeriod(startTime, endTime, mode);
        String filename = "tagging_statistic_" + language + ".xls";
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
        workbook.write(bufferedOutputStream);
        bufferedOutputStream.close();
        workbook.close();
//        return ResponseUtils.build(HttpStatus.OK.value(), "导出" + language + "标注数据成功！", result);
    }


}
